package com.nk.iexam.ds;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import com.nk.iexam.models.Question;

public class QuestionDataSource extends AbstractObjectDataSource<Question>
{
	public static final String TABLE_NAME = "tblQuestion";
	public static final String CATEGORY_ID = "CategoryID";
	public static final String CONTENT = "Content";
	public static final String COMMENT = "Comment";
	
	public QuestionDataSource() {
		super();
		_tableName = TABLE_NAME;
		_allColumnsName.add(CATEGORY_ID);
		_allColumnsName.add(CONTENT);
		_allColumnsName.add(COMMENT);
	}

	@Override
	protected Question cursorToObject(Cursor cursor_)
	{
		Question question = new Question();
		question.setId(cursor_.getLong(0));
		question.setCategoryId(cursor_.getInt(1));
		question.setContent(cursor_.getString(2));
		question.setComment(cursor_.getString(3));
		
		return question;
	}

	public Question create(final long categoryId_, final String content_, final String comment_) 
	{
		ContentValues values = new ContentValues();
		values.put(CATEGORY_ID, categoryId_);
		values.put(CONTENT, content_);
		values.put(COMMENT, comment_);
		
		long insertId = _database.insert(TABLE_NAME, null, values);
		Cursor cursor = _database.query(TABLE_NAME, getAllTableColumnsName(), ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		Question question = cursorToObject(cursor);
		cursor.close();
		return question;
	}
	
	public List<Question> getAllQuestionWithCategory(final long categoryId_)
	{
		List<Question> dbObjects = new ArrayList<Question>();
		Cursor cursor = _database.query(TABLE_NAME, getAllTableColumnsName(), "CategoryID = " + categoryId_, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Question dbObject = cursorToObject(cursor);
			dbObjects.add(dbObject);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return dbObjects;
	}
}
